package com.android.androidbigwork.utils;

import android.util.Log;
import com.android.androidbigwork.adapter.MySharesRequestParas;
import com.android.androidbigwork.entity.RequestParas;
import com.android.androidbigwork.entity.ShareOne;
import com.android.androidbigwork.pojo.LoginUser;
import okhttp3.*;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class RequestUtils {
    public static boolean flag = true;

    public final static int CONNECT_TIMEOUT = 60;
    public final static int READ_TIMEOUT = 100;
    public final static int WRITE_TIMEOUT = 60;
    public static final OkHttpClient client = new OkHttpClient.Builder().readTimeout(READ_TIMEOUT*2, TimeUnit.SECONDS)//设置读取超时时间
            .writeTimeout(WRITE_TIMEOUT*2, TimeUnit.SECONDS)//设置写的超时时间
            .connectTimeout(CONNECT_TIMEOUT*2, TimeUnit.SECONDS)//设置连接超时时间
            .build();
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    public static String get(String url) throws IOException{
        Request request = new Request.Builder().url(url).get().build();

        Response response = client.newCall(request).execute();
        if(response.isSuccessful())
            return response.body().string();
        else throw new IOException("GET请求抛出异常:"+response);
    }

    public static String post(String url,String json) throws IOException{
        RequestBody requestBody;

        requestBody = RequestBody.create(JSON,json);

        Request request = new  Request.Builder().url(url).post(requestBody).build();
        Response response = client.newCall(request).execute();
        if(response.isSuccessful())
            return response.body().string();
        else throw new IOException("POST请求抛出异常："+response);
    }

    public static  String postObj(ShareOne one , String url , Callback.CacheCallback<String> callback){

       RequestParams params = new RequestParams(url);
       params.addBodyParameter("userId",String.valueOf(one.getUserId()));
       params.addBodyParameter("message",one.getMessage());
       for(File file:one.getFileList()){
           params.addBodyParameter("fileList",file);
       }
        x.http().post(params,callback);
       return "";
    }

    public static <T>  void getShares(String url, Callback.CacheCallback<T> callBack){
        RequestParams params = new RequestParams(url);
        if (RequestUtils.flag)
           params.addBodyParameter("pageNum",String.valueOf(RequestParas.pageNum));
        else
            params.addBodyParameter("pageNum",String.valueOf(MySharesRequestParas.pageNum));

        params.addBodyParameter("pageSize",String.valueOf(RequestParas.pageSize));
        params.addBodyParameter("id",String.valueOf(LoginUser.getAccount()));

        x.http().post(params, callBack);
    }


}
